package com.xiaobu.go;

import com.xiaobu.chart.ChartBuilder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class StepActivity extends Activity
{
	private static final String TAG = "com.xiaobu.go.StepActivity";
	private StepPreferences mSettings;
	
	private StepService mService;
	
	private boolean mIsRunning = false;
	private boolean mIsBinding = false;
	private boolean mIsStoping = false;
	
	private TextView mStepValueView;
	private TextView mStepTextView;
	
	private StepHandler mHandler;
	
	private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = ((StepService.StepBinder)service).getService();
            mService.registerCallback(mCallback);
            mService.displaySteps();
        }
        public void onServiceDisconnected(ComponentName className) {
            mService.registerCallback(null);
            mService = null;
        }
    };
    
	private void startStepService()
    {
        if (!mIsRunning)
        {
            Log.i(TAG, "[SERVICE] Start");
            startService(new Intent(StepActivity.this, StepService.class));
            mSettings.saveServiceRunningWithTimestamp(true);
            mIsRunning = true;
        }
    }
    
    private void bindStepService()
    {
        Log.i(TAG, "[SERVICE] Bind");
        getApplicationContext().bindService(new Intent(StepActivity.this,
        		StepService.class), mConnection, Context.BIND_AUTO_CREATE + Context.BIND_DEBUG_UNBIND);
    }
    
    private void unbindStepService()
    {
        Log.i(TAG, "[SERVICE] Unbind");
        getApplicationContext().unbindService(mConnection);
    }
    
	private void stopStepService()
    {
        Log.i(TAG, "[SERVICE] Stop");
        if (mService != null)
        {
            Log.i(TAG, "[SERVICE] stopService");
            stopService(new Intent(StepActivity.this, StepService.class));
        }
        mSettings.saveServiceRunningWithNullTimestamp(false);
        mIsRunning = false;
    }
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mSettings = new StepPreferences(PreferenceManager.getDefaultSharedPreferences(this));
        mHandler = new StepHandler(this);
    }
    
    @Override
    protected void onPause()
    {
        Log.i(TAG, "[ACTIVITY] onPause");
        super.onPause();
        
        if (mIsBinding)
        {
            unbindStepService();
            mIsBinding = false;
        }
    }
    
    @Override
    protected void onResume()
    {
        Log.i(TAG, "[ACTIVITY] onResume");
        super.onResume();
        
        mIsRunning = mSettings.isServiceRunning();
        
        mStepValueView = (TextView) findViewById(R.id.step_value);
        //mStepValueView.getBackground().setAlpha(255);
        //mStepValueView.setBackgroundColor(0x0000FF);
        
        mStepTextView = (TextView) findViewById(R.id.step_units);
        //mStepTextView.getBackground().setAlpha(0);
        
        if (mIsRunning && !mIsBinding)
        {
        	bindStepService();
            mIsBinding = true;
        }
    }
    
    @Override
    protected void onStart()
    {
        Log.i(TAG, "[ACTIVITY] onStart");
        super.onStart();
        
        startStepService();
    }
    
    @Override
    protected void onStop()
    {
        Log.i(TAG, "[ACTIVITY] onStop");
        super.onStop();
        
        if (mIsBinding)
        {
        	unbindStepService();
        	mIsBinding = false;
        }
        
        if (mIsStoping)
        {
        	stopStepService();
        }
    }
    
    @Override
    protected void onDestroy()
    {
        Log.i(TAG, "[ACTIVITY] onDestroy");
        super.onDestroy();
    }
    
    private static final int MENU_HISTORY = 6;
    private static final int MENU_CHART = 7;
    private static final int MENU_SETTINGS = 8;
    private static final int MENU_QUIT = 9;

    private static final int MENU_PAUSE = 1;
    private static final int MENU_RESUME = 2;
    private static final int MENU_RESET = 3;
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        menu.clear();
        
        if (mIsRunning)
        {
            menu.add(0, MENU_PAUSE, 0, R.string.pause)
            .setIcon(android.R.drawable.ic_media_pause)
            .setShortcut('1', 'p');
        }
        else
        {
            menu.add(0, MENU_RESUME, 0, R.string.resume)
            .setIcon(android.R.drawable.ic_media_play)
            .setShortcut('1', 'p');
        }
        
        menu.add(0, MENU_RESET, 0, R.string.reset)
        .setIcon(android.R.drawable.ic_menu_close_clear_cancel)
        .setShortcut('2', 'r');
        
        menu.add(0, MENU_SETTINGS, 0, R.string.settings)
        .setIcon(android.R.drawable.ic_menu_preferences)
        .setShortcut('8', 's')
        .setIntent(new Intent(this, ChartBuilder.class));
        
        menu.add(0, MENU_HISTORY, 0, R.string.history)
        .setIcon(android.R.drawable.ic_menu_directions)
        .setShortcut('8', 'd')
        .setIntent(new Intent(this, ChartBuilder.class));
        
        menu.add(0, MENU_CHART, 0, R.string.chart)
        .setIcon(android.R.drawable.ic_menu_report_image)
        .setShortcut('8', 'c');
        
        menu.add(0, MENU_QUIT, 0, R.string.quit)
        .setIcon(android.R.drawable.ic_lock_power_off)
        .setShortcut('9', 'q');
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case MENU_PAUSE:
                unbindStepService();
                stopStepService();
                return true;
            case MENU_RESUME:
                startStepService();
                bindStepService();
                return true;
            case MENU_RESET:
                return true;
            case MENU_CHART:
            	int[] arrayOfInt = new int[2];
                Time time = new Time();
                time.setToNow();
                arrayOfInt[0] = time.hour;
                arrayOfInt[1] = (int)mService.getSteps();
                arrayOfInt[1] = 60;
            	Intent intent = new Intent(this, ChartBuilder.class);
            	intent.putExtra("hour_steps", arrayOfInt);
                StepActivity.this.startActivity(intent);
            	return true;
            case MENU_QUIT:
                unbindStepService();
                stopStepService();
                finish();
                return true;
        }
        
        return false;
    }
    
    private StepService.ICallback mCallback = new StepService.ICallback() {
        public void stepsChanged(int steps) {
            mHandler.sendMessage(mHandler.obtainMessage(StepHandler.STEPS_MSG, steps, 0));
        }
    };
    
    public static class StepHandler extends Handler
    {
    	private static final int STEPS_MSG = 1;
    	
    	private StepActivity mActivity = null;
    	
    	StepHandler(StepActivity stepActivity)
    	{
    		mActivity = stepActivity;
    	}
    	
    	@Override
        public void handleMessage(Message msg)
    	{
            switch (msg.what)
            {
                case STEPS_MSG:
                	//Log.i(TAG, "[ACTIVITY] STEPS_MSG");
                	mActivity.mStepValueView.setText("" + (int)msg.arg1);
                	mActivity.mStepValueView.getBackground().setAlpha(0); // opacity 180
                	mActivity.mStepValueView.setTextColor(0xFFFFFFFF); // text white
                	mActivity.mStepValueView.setBackgroundColor(0xB4F37300); //orange background
                    //mActivity.mStepValueView.setBackgroundColor(0xB4F39800);
                    
                	mActivity.mStepTextView.getBackground().setAlpha(0);
                	mActivity.mStepTextView.setTextColor(0xFFFFFFFF);
                	mActivity.mStepTextView.setBackgroundColor(0xB4F39800);
                    
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }
}